package org.shadow.process;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shadow.domain.HttpRequest;

import com.alibaba.fastjson.JSON;

//响应处理
public class HttpResponseProcess {

	private static Logger logger = LogManager.getLogger();

	private static Charset charset = Charset.forName("GBK");
	private static CharsetDecoder decoder = charset.newDecoder();

	public void process(SelectionKey key) {
		SocketChannel writerChannel = (SocketChannel) key.channel();
		HttpRequest request = (HttpRequest) key.attachment();
		logger.info("HttpResponseProcess process request param map is:{}", JSON.toJSONString(request));
		if (request == null) {
			return;
		}
		String page = request.getRequestPage();
		logger.info("HttpResponseProcess process request page is:{}", page);
		ByteBuffer readBytebuff = ByteBuffer.allocate(1024);
		CharBuffer charBuffer = CharBuffer.allocate(1024);
		StringBuffer contantBuff = new StringBuffer();
		try {
			if (page != null && page.indexOf(".") > 0) {
				URL filePath = HttpResponseProcess.class.getClassLoader()
						.getResource(page.substring(page.indexOf("/") + 1, page.length()));
				if (filePath != null) {
					File htmlFile = new File(filePath.getFile());
					if (htmlFile.exists()) {
						FileInputStream fileInputStream = new FileInputStream(htmlFile);
						FileChannel readFileChannel = fileInputStream.getChannel();
						int result = readFileChannel.read(readBytebuff);
						while (result > 0) {
							readBytebuff.flip();
							decoder.decode(readBytebuff, charBuffer, false);
							charBuffer.flip();
							contantBuff.append(new String(charBuffer.array()));
							charBuffer.clear();
							readBytebuff.clear();
							result = readFileChannel.read(readBytebuff);
						}
						if (fileInputStream != null) {
							fileInputStream.close();
						}
					}
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String httpResponse = "HTTP/1.1 200 OK\r\n" + "Content-Length: " + contantBuff.length() + "\r\n"
				+ "Content-Type: text/html;charset=utf-8\r\n" + "\r\n" + contantBuff.toString();
		try {
			ByteBuffer writerBuff = ByteBuffer.wrap(httpResponse.getBytes());
			writerChannel.write(writerBuff);
			writerChannel.shutdownInput();
			writerChannel.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
